package com.gec.teams.wechat.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.gec.teams.wechat.db.mapper.TbDeptMapper;
import com.gec.teams.wechat.db.mapper.TbUserMapper;
import com.gec.teams.wechat.db.pojo.MessageEntity;
import com.gec.teams.wechat.db.pojo.TbUser;
import com.gec.teams.wechat.exception.TeamsException;
import com.gec.teams.wechat.service.UserService;
import com.gec.teams.wechat.task.MessageTask;
import com.gec.teams.wechat.vo.TbUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
@Scope("prototype")
public class UserServiceImpl implements UserService {
    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private TbDeptMapper tbDeptMapper;

    private String getOpenId(String code){
        String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap map=new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response= HttpUtil.post(url,map);
        JSONObject json= JSONUtil.parseObj(response);
        String openId=json.getStr("openid");
        if(openId==null||openId.length()==0){
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }

    @Autowired
    private MessageTask messageTask;

    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        if(registerCode.equals("000000")){
            boolean bool=tbUserMapper.haveRootUser();
            if(!bool){
                String openId=getOpenId(code);

                TbUserVo tbUserVo = new TbUserVo();
                tbUserVo.setOpenId(openId);
                tbUserVo.setNickname(nickname);
                tbUserVo.setPhoto(photo);
                tbUserVo.setName(nickname);
                tbUserVo.setRole("[0]");
                tbUserVo.setHiredate(new Date());
                tbUserVo.setStatus(1);
                tbUserVo.setCreateTime(new Date());
                tbUserVo.setRoot(true);
                tbUserMapper.insertInt(tbUserVo);

                //功能测试系统消息收发.比如用户注册流程中,当用户成功注册的时候,我们就使用MessageTask异步发送消息到MQ队列中.
                MessageEntity entity = new MessageEntity();
                entity.setSenderId(0);//系统发送设为0
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎您注册成为超级管理员,请及时更新你的员工个人信息");
                entity.setSendTime(new Date());
                messageTask.sendAsync(tbUserVo.getId()+"",entity);

                return tbUserVo.getId();
            }
            else{//如果root账号被绑定了抛出异常
                throw new TeamsException("无法绑定超级管理员账号");
            }
        } else{
            //TODO普通员工注册
        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        return tbUserMapper.searchUserPermissions(userId);
    }


    //实现登录功能
    @Override
    public Integer login(String code) {
        String openId = getOpenId(code);
        Integer id = tbUserMapper.searchIdByOpenId(openId);
        if(id==null){
            throw new TeamsException("账户不存在");
        }
        //TODO 从消息队列中接收消息,转移到消息表
        messageTask.receiveAsync(id+"");
        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        return tbUserMapper.searchById(userId);
    }

    @Override
    public String searchUserHiredate(int userId) {
        return tbUserMapper.searchUserHiredate(userId);
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        return tbUserMapper.searchUserSummary(userId);
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap> list_1=tbDeptMapper.searchDeptMembers(keyword);
        ArrayList<HashMap> list_2=tbUserMapper.searchUserGroupByDept(keyword);
        //为部门添加员工
        for(HashMap map_1:list_1){
            long deptId=(Long)map_1.get("id");
            ArrayList members=new ArrayList();
            for(HashMap map_2:list_2){
                long id=(Long) map_2.get("deptId");
                if(deptId==id){
                    members.add(map_2);
                }
            }
            map_1.put("members",members);
        }
        return list_1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        return tbUserMapper.searchMembers(param);
    }

    @Override
    public ArrayList<HashMap> searchAllMembers() {
        return tbUserMapper.searchAllMembers();
    }

    @Override
    public ArrayList<HashMap> searchMembersDetail(List param) {
        return tbUserMapper.searchMembersDetail(param);
    }


}